package com.sun.plugin.aspose.templateReplace;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.regex.Pattern;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;

import com.aspose.words.ConvertUtil;
import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.IReplacingCallback;
import com.aspose.words.License;
import com.aspose.words.Node;
import com.aspose.words.NodeType;
import com.aspose.words.ReplacingArgs;
import com.aspose.words.Row;
import com.aspose.words.SaveFormat;
import com.sun.plugin.aspose.base.Teacher;
import com.sun.util.qrcode.QrCodeUtils;

/**
 * 实现水印
 * 实现二维码插入
 * 实现一对一，一对多模板替换
 *
 */
public class TemplateReplace {
	
	static{
		InputStream is = ConvertUtil.class.getResourceAsStream("/aspose/license.xml"); 
		License aposeLic = new License();
		try {
			aposeLic.setLicense(is);
		} catch (Exception e) {
		}
	}
	
	public static void main(String[] args) throws Exception {
		Teacher teacher = new Teacher();
		File file = new File("src/main/java/com/sun/plugin/aspose/templateReplace/Test.doc");
		if (!file.exists())
			return;
		Document document = new Document(new FileInputStream(file));
		for (Node rowNode : document.getChildNodes(NodeType.ROW, true).toArray()) {
			if (rowNode.getRange().getText().contains("^{students[")) {
				Row row = (Row) rowNode;
				for (int i = 0; i < teacher.getStudents().size(); i++) {
					Row extendRow = (Row) row.deepClone(true);
					extendRow.getRange().replace("num", i + "", true, false);
					row.getParentTable().insertBefore(extendRow, row);
				}
				row.remove();
				break;
			}
		}
		document.getRange().replace(Pattern.compile("\\^\\{(.*?)\\}"), new ReplacingCallbackPro(teacher), false);
		document.save("c://Test.doc", SaveFormat.DOC);
	}
}

class ReplacingCallbackPro implements IReplacingCallback {
	private Teacher teacher;

	public ReplacingCallbackPro(Teacher teacher) {
		this.teacher = teacher;
	}

	@Override
	public int replacing(ReplacingArgs rep) throws Exception {
		String p = StringUtils.trim(rep.getMatch().group(1));
		if (StringUtils.isNotBlank(p)) {
			if (p.equals("qrCode")) {
				Node node = rep.getMatchNode();
				// 获取当前文档
				Document doc = (Document) node.getDocument();
				DocumentBuilder builder = new DocumentBuilder(doc);
				// 将光标移动到指定节点
				builder.moveTo(node);
				// 插入图片
				builder.insertImage(QrCodeUtils.createImage("aaa"), 60, 60);
			} else {
				String val = String.valueOf(PropertyUtils.getProperty(teacher, p));
				rep.setReplacement(val);
			}
		}
		return 0;
	}
}
